package com.cloudlead.common.worker.web;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudlead.common.lang.api.ActionResponse.Level;
import com.cloudlead.common.lang.api.SimpleActionResponse;
import com.fasterxml.jackson.core.JsonParseException;

/**
 * Implementation of {@link ExceptionMapper} to send down a "400 Bad Request" in
 * the event unparsable JSON is received.
 */
@Provider
public class JsonParseExceptionMapper implements
		ExceptionMapper<JsonParseException> {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(JsonParseExceptionMapper.class);

	@Override
	public Response toResponse(JsonParseException ex) {
		LOGGER.error("json parse error", ex);

		SimpleActionResponse<String> result = new SimpleActionResponse<>(
				false, Level.error, ex.getMessage(),
				Response.Status.BAD_REQUEST.getStatusCode(),
				ex.getMessage());
		return Response.ok().entity(result)
				.type(MediaType.APPLICATION_JSON).build();
	}

}
